<?php

namespace App\Jobs;


use App\Libraries\Easemob\Easemob;
use App\Libraries\Tools\Msg;
use App\Models\HongBao\HongBao;
use App\Models\Msg\MsgSystem;
use App\Models\Tool\District;
use App\Models\User\User;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;

class GetMobileCityIdJob extends Job
{


    private $user_id;
    private $api;
    private $api_key;


    public function __construct($user_id)
    {
        $this->user_id = $user_id;
        $this->api = 'http://apis.juhe.cn/mobile/get';
        $this->api_key = 'bfd8843d224832e2cf6f2c2081227764';
    }

    /**
     * Execute the job.
     *
     * @param User $user
     * @param Client $client
     * @param District $district
     * @return bool
     * @throws \Exception
     */
    public function handle(User $user, Client $client, District $district)
    {
        $user = $user->where('user_id', $this->user_id)->firstOrFail();
        $data = $client->get($this->api.'?phone='.$user->mobile.'&key='.$this->api_key);
        $data = json_decode($data->getBody(), true);
        if($data['resultcode'] != 200){
            throw new \Exception('get mobile city id Fail in '.$user->mobile);
        }
        $district_data = $district->whereRaw('instr(name, "'.$data['result']['city'].'")')->where('type', 2)->first();
        if(empty($district_data)){
            $district_data = $district->whereRaw('instr(name, "'.$data['result']['city'].'")')->where('type', 3)->firstOrFail();
            $mobile_city_id = $district_data->parent_id;
        }else{
            $mobile_city_id = $district_data->id;
        }
        $user->mobile_city_id = $mobile_city_id;
        $user->save();
        return true;
    }
}
